package com.eric.test.thread.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: liuBing
 * @create: 2024-06-15 07:24
 **/
public class Create {

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                4,
                // 非核心线程存活的时间
                60,
                // 线程存活时间单位
                TimeUnit.SECONDS,
                // 队列类型
                new ArrayBlockingQueue<>(2),
                // 任务满了，拒绝策略
                new ThreadPoolExecutor.CallerRunsPolicy()
        );


        // 定义一个简单的任务
        Runnable task = () -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("Executing task in " + threadName);
            try {
                Thread.sleep(2000); // 模拟任务执行时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        };

        // 提交 6 个任务到线程池
        for (int i = 0; i < 6; i++) {
            threadPoolExecutor.submit(task);
        }

        // 关闭线程池
        threadPoolExecutor.shutdown();
    }
}
